package com.lujianfei.powersearch.widget

import android.app.DatePickerDialog
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.widget.AppCompatEditText
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Calendar

class DatePickerEditText @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatEditText(context, attrs) {

    var onTimeReceive:((timeStr:String, timeStamp:Long)->Unit) ?= null

    init {
        setOnTouchListener(object :OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                if (event?.action == MotionEvent.ACTION_DOWN) {
                    transferToYearMonthDay { year:Int, month:Int, dayOfMonth:Int->
                        showDatePickerDialog(year_in = year, month_in = month, dayOfMonth_in = dayOfMonth)
                    }
                    return true
                }
                return false
            }
        })
        setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                transferToYearMonthDay { year:Int, month:Int, dayOfMonth:Int->
                    showDatePickerDialog(year_in = year, month_in = month, dayOfMonth_in = dayOfMonth)
                }
            }
        }
    }

    private fun transferToYearMonthDay(callback:(year:Int, month:Int, dayOfMonth:Int)->Unit) {
        val dateStr = text.toString()
        val calendar = Calendar.getInstance()
        if (dateStr.isBlank()) {
            callback.invoke(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
        } else {
            val l = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            val unix = l.atStartOfDay(ZoneId.systemDefault()).toInstant().epochSecond
            calendar.timeInMillis = unix * 1000
            callback.invoke(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
        }
    }

    private fun showDatePickerDialog(year_in:Int, month_in:Int, dayOfMonth_in:Int) {
        val datePicker = DatePickerDialog(context, { view, year, month, dayOfMonth ->
            val timeStr = String.format("%04d-%02d-%02d", year, month + 1, dayOfMonth)
            val l = LocalDate.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            val unix = l.atStartOfDay(ZoneId.systemDefault()).toInstant().epochSecond
            onTimeReceive?.invoke(timeStr,unix)
        }, year_in, month_in, dayOfMonth_in)
        datePicker.show()
    }
}